package com.bilibili.liveremind.module.quartz.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bilibili.liveremind.module.entity.BaseUser;
import com.bilibili.liveremind.module.entity.LiveRoom;
import com.bilibili.liveremind.module.entity.UserLive;
import com.bilibili.liveremind.module.service.IBaseUserService;
import com.bilibili.liveremind.module.service.ILiveRoomService;
import com.bilibili.liveremind.module.service.IUserLiveService;
import com.bilibili.liveremind.module.util.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LiveRemindTask {

    @Autowired
    private ILiveRoomService liveRoomService;
    @Autowired
    private IUserLiveService userLiveService;
    @Autowired
    private IBaseUserService baseUserService;

    @Scheduled(cron = "0 */1 * * * ?")
    private void LiveRemind(){
        System.out.println("------ LiveRemind 提醒开始 ----------");
        LambdaQueryWrapper<LiveRoom> liveRoomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        liveRoomLambdaQueryWrapper.orderByDesc(LiveRoom::getCreateDate);
        List<LiveRoom> liveRoomList = liveRoomService.list(liveRoomLambdaQueryWrapper);
        for (LiveRoom liveRoom : liveRoomList) {
            String roomId = liveRoom.getRoomId();

            //获取直播状态
            //https://api.live.bilibili.com/xlive/web   -room/v2/index/getRoomPlayInfo?room_id=2322181&protocol=0,1&format=0,1,2&codec=0,1,2&qn=0&platform=web
            String biliRoomStatusUrl = "https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo";
            //参数
            Map<String, Object> biliRoomStatusUrlParam = new HashMap<>();
            biliRoomStatusUrlParam.put("room_id",roomId); //房间号
            //类似签名的参数
            biliRoomStatusUrlParam.put("protocol","0,1");
            biliRoomStatusUrlParam.put("format","0,1,2");
            biliRoomStatusUrlParam.put("codec","0,1,2");
            biliRoomStatusUrlParam.put("qn","0");
            biliRoomStatusUrlParam.put("platform","web");
            //使用hutool发送请求 get请求
            String liveResult = HttpUtil.get(biliRoomStatusUrl,biliRoomStatusUrlParam);
            JSONObject liveJson = JSONUtil.parseObj(liveResult);
            JSONObject liveDataJson = liveJson.getJSONObject("data");
            String liveStatus = liveDataJson.getStr("live_status");//直播状态 1已开播 0未开播(下播)
            Long liveStartTime = liveDataJson.getLong("live_time");//开播时间

            if ("1".equals(liveStatus)){

                //获取直播间信息
                String liveInfoResult = HttpUtil.get("https://live.bilibili.com/" + roomId);
                //使用正则表达式获取直播间信息
                List<String> liveInfoList = ReUtil.findAllGroup1("<script>window.__NEPTUNE_IS_MY_WAIFU__=(.*?)</script>", liveInfoResult);

                String liveTitle = "";
                String liveUname = "";
                String roomCover = "";
                String roomTag = "";
                if (liveInfoList.size()>0){
                    JSONObject obj = JSONUtil.parseObj(liveInfoList.get(0));
                    //直播标题
                    liveTitle = obj.getJSONObject("roomInfoRes").getJSONObject("data").getJSONObject("room_info").getStr("title");
                    //用户名称-房间号 liveUname-roomId
                    liveUname = obj.getJSONObject("roomInfoRes").getJSONObject("data").getJSONObject("anchor_info").getJSONObject("base_info").getStr("uname");
                    //直播封面
                    roomCover = obj.getJSONObject("roomInfoRes").getJSONObject("data").getJSONObject("room_info").getStr("cover");
                    roomCover = roomCover.replace("http:","https:").replaceAll("\\u002F","/");
                    //直播标签
                    roomTag = obj.getJSONObject("roomInfoRes").getJSONObject("data").getJSONObject("room_info").getStr("area_name");
                }
                //开播时间
                DateTime livePlayDate = DateUtil.date((liveStartTime*1000));
                LambdaQueryWrapper<UserLive> userLiveLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userLiveLambdaQueryWrapper.eq(UserLive::getRoomId,roomId);
                userLiveLambdaQueryWrapper.eq(UserLive::getStatus,1);
                userLiveLambdaQueryWrapper.eq(UserLive::getLiveStatus,0);
                userLiveLambdaQueryWrapper.eq(UserLive::getDeleteMark,0);
                userLiveLambdaQueryWrapper.orderByDesc(UserLive::getCreateDate);
                List<UserLive> userLiveList = userLiveService.list(userLiveLambdaQueryWrapper);

                for (UserLive userLive : userLiveList) {
                    BaseUser baseUser = baseUserService.getById(userLive.getUserId());
                    WxUtil.SendWxMessage(baseUser.getWxOpenId(),liveUname,roomId,liveTitle,livePlayDate);
                    userLive.setAnchorName(liveUname);
                    userLive.setRoomTitle(liveTitle);
                    userLive.setRoomCover(roomCover);
                    userLive.setRoomTag(roomTag);
                    userLive.setLiveStatus(1);
                }
                userLiveService.updateBatchById(userLiveList);
            }else if ("0".equals(liveStatus)){
                LambdaUpdateWrapper<UserLive> userLiveLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                userLiveLambdaUpdateWrapper.eq(UserLive::getRoomId,roomId);
                userLiveLambdaUpdateWrapper.eq(UserLive::getStatus,1);
                userLiveLambdaUpdateWrapper.eq(UserLive::getLiveStatus,1);
                userLiveLambdaUpdateWrapper.eq(UserLive::getDeleteMark,0);
                userLiveLambdaUpdateWrapper.set(UserLive::getLiveStatus,0);
                userLiveService.update(userLiveLambdaUpdateWrapper);
            }
        }
        System.out.println("------ LiveRemind 提醒结束 ----------");
    }
}
